<template>
  <div class="search-suggestion">
    <van-cell
      v-for="(text, index) in suggestions"
      :key="index"
      @click="$emit('search', text)"
      icon="search"
    >
      <div slot="title" v-html="highlight(text)"></div>
    </van-cell>
  </div>
</template>

<script>
import { debounce } from "lodash";
import { getSearchSuggestions } from "@/api/search";
export default {
  name: "SearchSuggestion",
  data() {
    return {
      suggestions: [], // 联想建议数据列表
    };
  },
  props: {
    searchText: {
      type: String,
      required: true,
    },
  },
  methods: {
    async loadSearchSuggestions(q) {
      try {
        const { data } = await getSearchSuggestions(q);
        this.suggestions = data.data.options;
      } catch (err) {
        this.$toast("获取联想数据失败");
      }
    },
    highlight(text) {
      const highlightStr = `<span class="active">${this.searchText}</span>`;
      const reg = new RegExp(this.searchText, "gi");
      return text.replace(reg, highlightStr);
    },
  },
  watch: {
    searchText: {
      handler: debounce(function (q) {
        this.loadSearchSuggestions(q);
      }, 300),
      immediate: true,
    },
  },
};
</script>

<style lang="less" scoped>
/deep/ .van-cell__title {
  .active {
    color: red !important;
  }
}
</style>>
